package com.basic.java.threads.sync.unsafe;

/**
 * 不安全的买票类
 * 创建时间：2022/4/19 22:03
 *
 * @author gejin
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket ticket = new BuyTicket();
        new Thread(ticket, "苦比的我---").start();
        new Thread(ticket, "牛逼的你---").start();
        new Thread(ticket, "可恶的黄牛---").start();
    }
}

class BuyTicket implements Runnable {
    // 初始票值
    private int ticketNums = 10;
    // 外部停止线程flag
    private boolean flag = true;

    @Override
    public void run() {
        // 买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void buy() throws InterruptedException {
        if (ticketNums <= 0) {// 如果剩余票小于0返回
            flag = false;
            return;
        }
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + "拿到了--->" + ticketNums--);
    }
}
